package com.durian.base.rxhttp

import okhttp3.Call
import java.util.concurrent.ConcurrentHashMap

/**
 * 说明：CallFactory
 * <p/>
 * 作者：fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2021/10/21 3:36 下午
 * <p/>
 * 版本：version 1.0
 */
object CallCancelFactory {

    private val callMap = ConcurrentHashMap<String,Call>()

    fun cancelAll(){
        callMap.onEach {
            if (!it.value.isCanceled()){
                it.value.cancel()
            }
        }
        callMap.clear()
    }

    fun addCall(tag : String,call: Call){
        if (tag.isNotEmpty()){
            cancelCall(tag)
            callMap[tag] = call
        }
    }

    fun cancelCall(tag : String){
        callMap[tag]?.let {
            if (!it.isCanceled()){
                it.cancel()
            }
        }
        removeCall(tag)
    }

    fun removeCall(tag : String){
        if (tag.isNotEmpty()){
            callMap.remove(tag)
        }
    }

}